<?php

use Core\ResourceController;
use Models\Category;
use Models\Product;

class CategoryController extends ResourceController
{
    public function index()
    {
        $categories = Category::where('parent_id', 0)->order_by('sort desc')->get();

        // 获取热卖产品
        $products = [];
        $sub_categories = [];
        if ($categories) {
            $category = $categories[0];
            $sub_categories = Category::where('parent_id', $category['id'])->get();

            $categories[0]['sub_categories'] = $sub_categories;

            $category_ids = array_reduce($sub_categories, function ($carry, $item) {
                if (!$carry) {
                    $carry = [];
                }
                $carry[] = $item['id'];

                return $carry;
            });
            $category_ids[] = $category['id'];

            $products = Product::select('id,thumbnail,title,en_title')->where_in('category_id', $category_ids)->where('status', 1)->order_by('sort desc,solded desc')->limit(10)->get();

            $categories[0]['products'] = $products;
        }

        return $this->response($categories);
    }

    //获取分类详情
    public function detail($id)
    {
        $category = (new Category)->find($id);
        if (!$category) {
            return $this->notFoundResponse();
        }
        $sub_categories = Category::where('parent_id', $category['id'])->get();
        $category_ids = array_reduce($sub_categories, function ($carry, $item) {
            if (!$carry) {
                $carry = [];
            }
                $carry[] = $item['id'];

                return $carry;
        });
        $category_ids[] = $id;

        $products = Product::select('id,thumbnail,title,en_title')->where_in('category_id', $category_ids)->order_by('solded desc')->limit(10)->get();

        return $this->response([
            'category' => $category,
            'sub_categories' => $sub_categories,
            'products' => $products,
        ]);
    }
}
